package com.woniu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.entity.Result;
import com.woniu.user.mapper.UserMapper;
import com.woniu.user.pojo.Praise;
import com.woniu.user.mapper.PraiseMapper;
import com.woniu.user.pojo.User;
import com.woniu.user.service.IPraiseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 点赞表 服务实现类
 * </p>
 *
 * @author LiFangyu
 * @since 2023-02-15
 */
@Service
public class PraiseServiceImpl extends ServiceImpl<PraiseMapper, Praise> implements IPraiseService {

    @Autowired(required = false)
    private PraiseMapper praiseMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result like(String phone,String article) {
        User user = get(phone);

        // 将点赞信息存入Redis
        String key = "user_" + phone+"_"+article;
        redisTemplate.opsForHash().put(key, "userId", user.getId());
        redisTemplate.opsForHash().put(key, "likeState", 1);
        redisTemplate.opsForHash().put(key, "article", article);

        return Result.ok(200);
    }

    @Override
    public Result cancelLike(String phone,String article) {
        // 查询 Redis，判断该用户是否点过赞
        String key = "user_" + phone+ "_" +article;
        if (redisTemplate.hasKey(key)) {
            // 更新点赞状态
            redisTemplate.opsForHash().put(key, "likeState", 0);
            redisTemplate.opsForHash().put(key, "article", article);
        }

        return Result.ok(200);
    }


    private User get(String phone){
        return praiseMapper.getUser(phone);
    }


    /**
     * 定时任务，定时从Redis中获取key-value并同步数据到MySQL
     */
    @Scheduled(fixedRate = 10000)  // 任务以10秒为间隔重复执行
    public void syncRedisData() {
        // 获取Redis中指定key-value记录
        Set keys = redisTemplate.keys("user_*");
        for (Object key : keys) {
            Map entries = redisTemplate.opsForHash().entries(key);
            Praise praise = new Praise();
            praise.setStatus(entries.get("likeState").toString());
            praise.setUserId(entries.get("userId").toString());
            praise.setArticleId(entries.get("article").toString());
            Praise isPraise = praiseMapper.selectIsPraise(entries.get("userId").toString(),entries.get("article").toString());
            if (isPraise == null){
                praiseMapper.insert(praise);
            }
        }
    }



//    @Scheduled(fixedRate = 10000)  //  任务以10秒为间隔重复执行
//    public void syncRedisData() {
//        Set keys = redisTemplate.keys("user_*");
//        //利用Map对Redis中的记录进行去重
//        Map<String, Praise> redisMap = new HashMap<>();
//        for (Object key : keys) {
//            Map entries = redisTemplate.opsForHash().entries(key);
//            Praise praise = new Praise();
//            praise.setStatus(entries.get("likeState").toString());
//            praise.setUserId(entries.get("userId").toString());
//            praise.setArticleId(entries.get("article").toString());
//            redisMap.put(praise.getArticleId(), praise);//根据ArticleId来去重
//        }
//
//        //将去重数据写入数据库
//        Iterator<Map.Entry<String, Praise>> it = redisMap.entrySet().iterator();
//        while (it.hasNext()) {
//            Map.Entry<String, Praise> entry = it.next();
//            Praise praise = entry.getValue();
//            praiseMapper.insert(praise);
//        }
//    }

}
